package com.zdj.presentation.modules.login.views;

import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.zdj.aoplibrary.annotations.SecurityCheckAnnotation;
import com.zdj.aoplibrary.util.PermissionsConstants;
import com.zdj.aoplibrary.util.SecurityCheckManager;
import com.zdj.data.entity.DaoMaster;
import com.zdj.data.entity.DaoSession;
import com.zdj.data.entity.LoginDao;
import com.zdj.presentation.R;
import com.zdj.presentation.base.BaseActivity;
import com.zdj.presentation.databinding.ActivityLoginBinding;
import com.zdj.presentation.modules.login.vms.LoginVm;
import com.zdj.utils.MyLogUtil;

public class LoginActivity extends BaseActivity<LoginVm, ActivityLoginBinding> {

    private SQLiteDatabase db;

    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private LoginDao loginDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化 权限验证模块
        SecurityCheckManager.createInstance(this);

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "login-db", null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    @Override
    protected void initVms() {
        viewModel = new LoginVm(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void setViewModel2Binding() {
        viewDatabinding.setLoginVm(viewModel);
    }

    @Override
    protected void initView() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PermissionsConstants.RECORD_AUDIO_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                realDoLogin();
            } else {
                showToast("取消授予电话状态权限");
            }
        }
    }
    @SecurityCheckAnnotation(declaredPermission = "android.permission.READ_PHONE_STATE")
    private void realDoLogin(){
        MyLogUtil.e(TAG, "doLogin: 点击登陆按钮了");
        Cursor query = db.query(loginDao.getTablename(), new String[]{LoginDao.Properties.Username.name, LoginDao.Properties.Password.name}, null, null, null, null, null);
        if (query.moveToNext()) {
            if (query.getCount() == 1) {
                showToast("可以登陆");
            } else {
                showToast("有多个重复的账号");
            }
        } else {
            showToast("账号或者密码错误");
        }
    }
}
